import time
import jwt
import datetime
from datetime import timedelta
import uuid
from sqlalchemy.orm import Session
from database import SessionLocal
from models import SysUser, LoginSession, InviteCode
import os

from utils.jwt_utils import ACCESS_TOKEN_EXPIRE_MINUTES, ALGORITHM, SECRET_KEY, create_access_token, create_refresh_token


def register_user(username: str, password: str, email: str, invite_code: str, db: Session):
        # 验证邀请码
        db_code = db.query(InviteCode).filter(InviteCode.code == invite_code, InviteCode.is_used == 0).first()
        if not db_code:
            return {"error": "无效或已使用的邀请码"}
        
        # 检查用户名/邮箱唯一性
        if db.query(SysUser).filter(SysUser.username == username).first():
            return {"error": "用户名已存在"}
        if db.query(SysUser).filter(SysUser.email == email).first():
            return {"error": "邮箱已存在"}
        
        # 创建用户
        new_user = SysUser(
            username=username,
            password=password,
            email=email,
            created_at=int(time.time())
        )
        db.add(new_user)
        
        # 标记邀请码为已使用
        db_code.is_used = 1
        
        db.commit()
        db.refresh(new_user)
        return {"message": "注册成功"}

def login_user(username: str, password: str, db: Session):

        # 查询用户
        db_user = db.query(SysUser).filter(SysUser.username == username, SysUser.password == password).first()
        if not db_user:
            return {"error": "用户名或密码错误"}
        
        # 生成token 
        token_data = {"sub": username}
        access_token = create_access_token(token_data)
        refresh_token = create_refresh_token(token_data)
        
        
        # 创建登录会话
        new_session = LoginSession(
            user_id=db_user.id,
            token=access_token,
            created_at=int(time.time()),
            expires_at=int(time.time()) + ACCESS_TOKEN_EXPIRE_MINUTES * 60,
            is_active=1
        )
        db.add(new_session)
        db.commit()
        db.refresh(new_session)
        return {"access_token": access_token, "token_type": "bearer"}


def generate_invite_code(db: Session):
    code = str(uuid.uuid4())
    new_invite = InviteCode(
        code=code,
        created_at=int(time.time())
    )
    db.add(new_invite)
    db.commit()
    db.refresh(new_invite)
    return {"code": code}
    
def logout_user(token: str, db: Session):
    try:
        # 验证JWT
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            return {"error": "无效的token"}
        
        # 更新会话状态
        updated = db.query(LoginSession).filter(
            LoginSession.token == token,
            LoginSession.is_active == 1
        ).update({"is_active": 0})
        db.commit()
        
        if updated > 0:
            return {"message": "登出成功"}
        return {"error": "会话已过期或无效"}
    except jwt.ExpiredSignatureError:
        return {"error": "token已过期"}
    except jwt.InvalidTokenError:
        return {"error": "无效的token"}
        
def check_login_status(token: str, db: Session):
    try:
        # 验证JWT
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            return {"error": "无效的token"}
        db_user = db.query(SysUser).filter(SysUser.username == username).first()
        if not db_user:
            return {"error": "用户不存在"}
        
        # 检查有效会话
        current_time = int(time.time())
        db_session = db.query(LoginSession).filter(
            LoginSession.user_id == db_user.id,
            LoginSession.token == token,
            LoginSession.is_active == 1,
            LoginSession.expires_at > current_time
        ).first()
        
        if db_session:
            return {"username": username, "is_valid": True}
        return {"error": "会话已过期或无效"}
    except jwt.ExpiredSignatureError:
        return {"error": "token已过期"}
    except jwt.InvalidTokenError:
        return {"error": "无效的token"}
    
def get_user(token: str, db: Session):
    try:
        # 验证JWT
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if not username:
            return {"error": "无效的token"}
        db_user = db.query(SysUser).filter(SysUser.username == username).first()
        if not db_user:
            return None
        return db_user
    except jwt.ExpiredSignatureError:
        return None
    except jwt.InvalidTokenError:
        return None